const cloud = require('wx-server-sdk')

cloud.init()

/// (id: BookId, location: LocationString, user: User?) => (StatusCode, PoolId?)
/// StatusCode:

const SUCCESS = 0;
const BAD_ARGUMENT = -1;
const NOT_FOUND = -2;
const NOT_PRESENT = -3;

exports.main = async (event) => {
  const id = event.id;
  const location = event.location;
  const user = event.user; // nullable

  if (id == null || location == null) {
    return {
      code: BAD_ARGUMENT
    };
  }

  const db = cloud.database();

  let res;

  try {
    res = await db.collection('books').doc(id).get();
    if (res == null) {
      return {
        code: NOT_FOUND
      };
    }
  } catch (e) {
    return {
      code: NOT_FOUND
    };
  }

  const book = res.data;

  for (let i = 0; i < book.location.length; i++) {
    if (book.location[i].location == location) {
      if (book.location[i].present) {
        const key = `location.${i}.present`;
        const query = {};
        query[key] = false;
        await db.collection('books').doc(id).update({
          data: query
        });
        const res = await db.collection('pool').add({
          data: {
            book: id,
            time: Date.now(),
            target: user
          }
        });
        return {
          code: SUCCESS,
          result: res._id
        };
      } else {
        return {
          code: NOT_PRESENT
        };
      }
    }
  }

  return {
    code: NOT_FOUND
  };
}
